﻿using FC.ERP.TMom.Api.AppHandlers.Commands;
using FC.ERP.TMom.Api.DTOs;
using FC.ERP.TMom.Domain;
using FC.ERP.TMom.ErrorCode;
using FC.ERP.TMom.Infrastructure.Interfaces;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace FC.ERP.TMom.Api.AppHandlers.CommandHandlers
{
    public class LoginQuertyCommandHandler : IRequestHandler<LoginQuertyCommand, APIResult<SyUserDto>>
    {
        private readonly IBaseRepository<SyUser> syUserrepository;
        private readonly IBaseRepository<SysRole> sysRolerepository;
        private readonly IBaseRepository<SysUserRole> sysUserRolerepository;

        public LoginQuertyCommandHandler(IBaseRepository<SyUser> syUserrepository, IBaseRepository<SysRole> sysRolerepository, IBaseRepository<SysUserRole> sysUserRolerepository)
        {
            this.syUserrepository = syUserrepository;
            this.sysRolerepository = sysRolerepository;
            this.sysUserRolerepository = sysUserRolerepository;
        }
        public Task<APIResult<SyUserDto>> Handle(LoginQuertyCommand request, CancellationToken cancellationToken)
        {
            APIResult<SyUserDto> result = new APIResult<SyUserDto>();
            result.Code = ResultCode.登录成功;
            result.Message = ResultCode.登录成功.ToString();

            var list = from a in syUserrepository.GetAll()
                       join b in sysUserRolerepository.GetAll() on a.UserId equals b.UserId
                       join c in sysRolerepository.GetAll() on b.RoleId equals c.RoleId
                       where a.LoginAccoun == request.LoginAccoun && a.Password == request.Password
                       select new SyUserDto
                       {
                           UserId = a.UserId,
                           LoginAccoun = a.LoginAccoun,
                           Password = a.Password,
                           RealName = a.RealName,
                           RoleId = c.RoleId,
                           RoleName = c.RoleName,
                       };
            var entity = list.FirstOrDefault();

            if (entity == null)
            {
                result.Code = ResultCode.登录失败;
                result.Message = ResultCode.登录失败.ToString();
            }

            entity.token = CreateTokenString(entity);
            result.Data = entity;

            return Task.FromResult(result);
        }

        private string CreateTokenString(SyUserDto dto)
        {
            // 1. 先检查 dto 是否为 null（防御性编程）
            if (dto == null)
            {
                throw new ArgumentNullException(nameof(dto), "用户信息不能为空，无法生成令牌");
            }

            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            var signingKey = new SymmetricSecurityKey(secretByte);
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            // 2. 对可能为 null 的属性使用 ?.ToString() ?? "" 避免空引用
            var claims = new[]
            {
                new Claim("UserId", dto.UserId.ToString()),
                new Claim("LoginAccoun", dto.LoginAccoun.ToString()),
                new Claim("RealName", dto.RealName.ToString()),
                new Claim("RoleId", dto.RoleId.ToString()),
                new Claim("RoleName", dto.RoleName.ToString()),
            };

            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1),
                claims: claims,
                signingCredentials: signingCredentials
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

    }

}
